package com.example.messagemodule.widget;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.examination.mlib.constants.AllStringConstants;
import com.example.messagemodule.R;
import com.example.messagemodule.entity.ChargeEntity;
import com.example.messagemodule.entity.EntryGroupEntity;
import com.example.messagemodule.entity.EntryImEntity;
import com.hyphenate.chat.EMMessage;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.DataUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by SHICHENG
 * <p>
 * Time on
 */
public class InquiryStatusView extends LinearLayout {

    View view;
    LinearLayout conversationStatus;
    TextView inquiryStatus;
    TextView inquiryTime;
    TextView inquiryFinish;
    ArrayList<ChargeEntity> chargeEntities;
    boolean isWaitting;
    boolean isEnd;
    boolean isUploadImage;

    private long inquriyTimes = 0;
    String chargesVisitTime;
    EMMessage.ChatType chatType;
    EntryImEntity.DataBean entryData;
    EntryGroupEntity.DataBean entryGroupData;
    int type;
    private Timer timer;
    private TimerTask timerTask;
    Handler handler;
    private OnInquiryStatusComplent onInquiryStatusComplent;

    public InquiryStatusView(Context context) {
        super(context);init();
    }

    public InquiryStatusView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);init();
    }

    public InquiryStatusView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);init();
    }

    public InquiryStatusView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    void init(){
        timer  = new Timer();
        handler = new Handler();

        chargeEntities = new ArrayList<>();
        chargeEntities.add(new ChargeEntity("waiting", "待接诊", "24小时未接诊自动退诊退费"));
        chargeEntities.add(new ChargeEntity("interrogation", "问诊中", "秒后问诊结束"));
        chargeEntities.add(new ChargeEntity("followuping", "随访中", "秒后随访结束"));
        chargeEntities.add(new ChargeEntity("queryResidueing", "咨询中", "秒后咨询结束"));
        chargeEntities.add(new ChargeEntity("escCharge", "已退诊", "问诊已退诊"));
        chargeEntities.add(new ChargeEntity("end", "已结束", "问诊已完成，感谢使用"));
        chargeEntities.add(new ChargeEntity("followupend", "已结束", "随访已完成，感谢使用"));
        chargeEntities.add(new ChargeEntity("queryResidueend", "已结束", "咨询已完成，感谢使用"));
        chargeEntities.add(new ChargeEntity("timeline", "已结束", "问诊超时已取消"));
        chargeEntities.add(new ChargeEntity("waittingAudit", "待审核", "已通知医生尽快审核"));
        chargeEntities.add(new ChargeEntity("waittingStart", "待开始", "预约已确认，请按时就诊"));
        chargeEntities.add(new ChargeEntity("patinetsCancal", "已取消", "您已取消本次问诊"));
        chargeEntities.add(new ChargeEntity("doctorNoAudit", "已取消", "医生已拒绝本次问诊，请重新预约"));
        chargeEntities.add(new ChargeEntity("systemCheckCancel", "已取消", "系统审核不通过取消"));
        chargeEntities.add(new ChargeEntity("peopleCheckCancel", "已取消", "审核人员审核不通过取消"));
        chargeEntities.add(new ChargeEntity("inquiryCancel", "已退诊", "已退诊失效"));

        view = LayoutInflater.from(getContext()).inflate(R.layout.view_inquiry_status, this);
        conversationStatus = (LinearLayout) view.findViewById(R.id.conversation_status);
        inquiryStatus = (TextView) view.findViewById(R.id.inquiry_status);
        inquiryTime = (TextView) view.findViewById(R.id.inquiry_time);
        inquiryFinish = (TextView) view.findViewById(R.id.inquiry_finish);

        inquiryFinish.setOnClickListener(v -> finish_inquiry());

    }

    public void refreshStatus(EntryImEntity.DataBean entryData){
        this.entryData = entryData;
        chatType = EMMessage.ChatType.Chat;
        chargesVisitTime = entryData.getImChargesList().getChargesVisitTime();
        int status = entryData.getImChargesList().getChargesListStatus();
        type = entryData.getImChargesList().getType();
        ChargeEntity chargeStatus = getChargeStatus(status);
        initStatus(chargeStatus);
    }

    public void refreshStatus(EntryGroupEntity.DataBean entryGroupData){
        this.entryGroupData = entryGroupData;
        chatType = EMMessage.ChatType.GroupChat;
        chargesVisitTime = entryGroupData.getImTeamChargesList().getChargesVisitTime();
        int status = entryGroupData.getImTeamChargesList().getChargesListStatus();
        type = entryGroupData.getImTeamChargesList().getType();
        ChargeEntity chargeStatus = getChargeStatus(status);
        initStatus(chargeStatus);
    }

    ChargeEntity getChargeStatus(int status) {
        String isChargeEnd = null;
        isWaitting = false;
        isEnd = false;
        if (status == 5) {
            isChargeEnd = "waiting";
            isWaitting = true;
            isEnd = true;
        } else if (status == 2) { // 咨询中
            if (chatType == EMMessage.ChatType.Chat) {
                if (type == 5) {
                    isChargeEnd = "followuping";
                } else if (type == 8) {
                    isChargeEnd = "queryResidueing";
                    inquiryFinish.setVisibility(View.VISIBLE);
                } else {
                    isChargeEnd = "interrogation";
                }
            } else {
                if (type == 5) {
                    isChargeEnd = "followuping";
                } else {
                    isChargeEnd = "interrogation";
                }
            }
            isEnd = false;
            isUploadImage = false;
        } else if (status == 3) { // 结束问诊
            if (chatType == EMMessage.ChatType.Chat) {
                if (type == 5) {
                    isChargeEnd = "followupend";
                } else if (type == 8) {
                    isChargeEnd = "queryResidueend";
                } else {
                    isChargeEnd = "end";
                }
            } else {
                if (type == 5) {
                    isChargeEnd = "followupend";
                } else if (type == 8) {
                    isChargeEnd = "queryResidueend";
                } else {
                    isChargeEnd = "end";
                }
            }
            isEnd = true;
        } else if (status == 4) { // 待接诊时超时取消
            isChargeEnd = "timeline";
            isEnd = true;
        } else if (status == 7 || status == 10) { // 医生退诊  医生取消
            isChargeEnd = "escCharge";
            isEnd = true;
        } else if (status == 0) { // 待审核
            isChargeEnd = "waittingAudit";
            isEnd = true;
        } else if (status == 1) { // 待开始
            isChargeEnd = "waittingStart";
            isEnd = true;
        } else if (status == 11 || status == 8) { // 患者取消
            isChargeEnd = "patinetsCancal";
            isEnd = true;
        } else if (status == 9) { // 医生审核不通过
            isChargeEnd = "doctorNoAudit";
            isEnd = true;
        } else if (status == 12) {
            isChargeEnd = "systemCheckCancel";
            isEnd = true;
        } else if (status == 13) {
            isChargeEnd = "peopleCheckCancel";
            isEnd = true;
        } else if (status == 16) {
            isChargeEnd = "inquiryCancel";
            isEnd = true;
        }
        for (int i = 0; i < chargeEntities.size(); i++) {
            if (chargeEntities.get(i).getCharge_status().equals(isChargeEnd)) {
                return chargeEntities.get(i);
            }
        }
        return null;
    }

    void initStatus(ChargeEntity chargeStatus){
        //        ChargeEntity chargeStatus = getChargeStatus(status);
        if (chatType == EMMessage.ChatType.GroupChat && entryGroupData.getWaitTime() > 0) {
            setInquriyStatus("问诊中", entryGroupData.getWaitTimeShow(), "interrogation");
        } else if (chargeStatus != null) {
            if (chargeStatus.getCharge_title() == null) {

            } else if (chargeStatus.getCharge_subTitle() == null) {

            } else if (chargeStatus.getCharge_status() == null) {

            } else {
                if (type == 3 && TextUtils.equals("waiting",chargeStatus.getCharge_title())){
                    setInquriyStatus(chargeStatus.getCharge_title(), "", chargeStatus.getCharge_status());
                }else{
                    setInquriyStatus(chargeStatus.getCharge_title(), chargeStatus.getCharge_subTitle(), chargeStatus.getCharge_status());
                }
            }
            if (onInquiryStatusComplent == null){
                return;
            }
            if (isWaitting) {
                onInquiryStatusComplent.waiting();

            } else {
                onInquiryStatusComplent.noWaiting();
            }
            if (isEnd) {
                if (!isWaitting) {
                    if (chatType == EMMessage.ChatType.Chat) {
                        //单聊
                        if (timer != null) {
                            timer.cancel();
                        }
                        onInquiryStatusComplent.ending();
                    } else if (chatType == EMMessage.ChatType.GroupChat) {
                        //群聊

                    }
                }
            } else {
                onInquiryStatusComplent.noEnding();
                try {
                    long l = DataUtils.string2long(chargesVisitTime, "yyyy-MM-dd HH:mm:ss");
//                    long l1 = 60 * 60 * 1000 * 24 - System.currentTimeMillis() + l;
//                    long l1 = DataUtils.stringToLong(entryData.getImChargesList().getChargesEndTime(),"yyyy-MM-dd  HH:mm:ss") - System.currentTimeMillis() + l;
                    long l1 = 0;
                    if (chatType == EMMessage.ChatType.Chat) {
                        ALog.e(entryData.getImChargesList().getPatientChargesEndTime());
                        ALog.e(System.currentTimeMillis() + "");
                        l1 = Long.valueOf(entryData.getImChargesList().getPatientChargesEndTime()).longValue() - System.currentTimeMillis();
                    } else if (chatType == EMMessage.ChatType.GroupChat) {
                        l1 = Long.valueOf(entryGroupData.getImTeamChargesList().getChargesEndTime()).longValue() - System.currentTimeMillis();
                    }
//                    DataUtils.longToString(l1,"yy-mm-dd HH:mm:ss")
                    if (l1 <= 0) {
//                        setInquriyStatus(chargeStatus.getCharge_title(), count_downText(0), chargeStatus.getCharge_status());
                        setInquriyStatus(chargeStatus.getCharge_title(), chatType == EMMessage.ChatType.Chat ? "已到达结束时间,请等待医生处理" : "", chargeStatus.getCharge_status());
                    } else {
                        setInquriyStatus(chargeStatus.getCharge_title(), count_downText(l1 / 1000), chargeStatus.getCharge_status());
                    }
                    if (l1 > 0) {
                        if (chatType == EMMessage.ChatType.Chat) {
                            inquiryTime.setVisibility(View.VISIBLE);
                            count_down(l1 / 1000);
                        } else {
                            inquiryTime.setVisibility(View.GONE);
                        }
                    } else {
                        if (entryData.getImChargesList().getType() == 8) {
                            finish_inquiry();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }


        }
    }

    //设置倒计时文本
    String count_downText(long time) {
        long minute = time / 60;
        long hours = 0;
        long minutes = 0;
        long seconds = 0;
        long days = 0;
        seconds = time % 60;
        hours = minute / 60 % 24;
        days = time / 60 / 60 / 24;
        minutes = minute % 60;
        String timestring = String.format("%02d", hours) + "小时" + String.format("%02d", minutes) + "分" + String.format("%02d", seconds) + "秒后" + (type == 5 ? "随访" : type == 8 ? "咨询" : "问诊") + "结束";
        if (days > 0) {
            return String.format("%02d", days) + "天" + timestring;
        } else {
            return timestring;
        }
    }

    private void finish_inquiry() {
        RequestParams params = new RequestParams();
        params.put("chargesListId", entryData.getImChargesList().getChargesListId());
        HttpUtils.get(AllStringConstants.MessageUrl.finishChargesList, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s, int i) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.has("result") && jsonObject.getBoolean("result")) {
                        findViewById(R.id.inquiry_finish).setVisibility(View.GONE);
                        onInquiryStatusComplent.finishInquiry();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }



    //设置问诊状态
    void setInquriyStatus(String inquiryStatusText, String finishStatus, String chargeStatus) {
        if (chatType == EMMessage.ChatType.Chat) {
            inquiryStatus.setText(inquiryStatusText);
            inquiryTime.setText(finishStatus);
            if (TextUtils.equals(chargeStatus, "waittingStart")) {
                onInquiryStatusComplent.refreshAppointmentPicWait();
            } else {
                onInquiryStatusComplent.refreshInquiryEndHint(chargeStatus);
            }
        } else if (chatType == EMMessage.ChatType.GroupChat) {
            inquiryStatus.setText(inquiryStatusText);
            inquiryTime.setText(finishStatus);
            if ("end".equals(chargeStatus)) {
//                        tvEndTitle.setText("问诊已结束");
//                        endImPopupLl.setVisibility(View.VISIBLE);
            } else if ("followupend".equals(chargeStatus)) {
//                        tvEndTitle.setText("随访已结束");
//                        endImPopupLl.setVisibility(View.VISIBLE);
            } else {
//                        endImPopupLl.setVisibility(View.GONE);
            }
        }

    }

    //倒计时设置
    void count_down(long time) {
        inquriyTimes = time;
        if (timer == null) {
            timer = new Timer();
        }
        timerTask = new TimerTask() {
            @Override
            public void run() {
                inquriyTimes--;
                if (inquriyTimes <= 0) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (entryData.getImChargesList().getType() == 5) {
                                inquiryTime.setText("随访已完成，感谢使用");
                            } else if (entryData.getImChargesList().getType() == 8) {
                                inquiryTime.setText("咨询已完成，感谢使用");
                                finish_inquiry();
                            } else {
                                inquiryTime.setText("问诊已完成，感谢使用");
                            }
                            inquiryStatus.setText("已结束");
                            timer.cancel();
                            onInquiryStatusComplent.refreshChargeUi(3);
                        }
                    });

                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (inquriyTimes > 0) {
                            String s = count_downText(inquriyTimes);
                            inquiryTime.setText(s);
                        }
                    }
                });
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    public void setOnInquiryStatusComplent(OnInquiryStatusComplent onInquiryStatusComplent) {
        this.onInquiryStatusComplent = onInquiryStatusComplent;
    }



    public interface OnInquiryStatusComplent{

        void waiting();

        void noWaiting();

        void ending();

        void noEnding();

        void finishInquiry();

        void refreshAppointmentPicWait();

        void refreshInquiryEndHint(String chargeStatus);

        void refreshChargeUi(int status);
    }
}
